import streamlit as st
import pandas as pd
from analyzelogics.logistics_cost import logistics_cost_estimate as lc

# 创建中文到国家代码的反向映射
# 处理重复值：列支敦士登有两个代码(LI和FL)，我们统一使用LI

# 创建中文到国家代码的反向映射
cn_to_country_code = {}
# 用于保持原始顺序的国家选项列表
country_options = []

# 假设 lc.country_code_to_cn 已定义
for code, cn_name in lc.country_code_to_cn.items():
    # 跳过FL，使用LI代表列支敦士登
    if cn_name == "列支敦士登" and code == "FL":
        continue

    # 添加到反向映射
    cn_to_country_code[cn_name] = code

    # 添加到选项列表（保持原始顺序）
    if cn_name not in country_options:
        country_options.append(cn_name)

# 初始化session_state
if "erpsku" not in st.session_state:
    st.session_state["erpsku"] = None
if "country" not in st.session_state:
    st.session_state["country"] = None
if "zip_code" not in st.session_state:
    st.session_state["zip_code"] = None
if "province" not in st.session_state:
    st.session_state["province"] = None  # 新增省份字段


st.title("物流成本计算器")

col1, col2, col3 = st.columns(3)
with col1:
    st.session_state["country"] = st.selectbox('国家', country_options)
with col2:
    st.session_state["erpsku"] = st.text_input('ERP SKU')
with col3:
    st.session_state["zip_code"] = st.text_input('邮编')

# 当选择加拿大时显示省份输入框，否则隐藏
if st.session_state["country"] == "加拿大":
    st.session_state["province"] = st.text_input('省份（加拿大必填）', key="province_input")
else:
    # 如果不是加拿大，清空省份字段
    st.session_state["province"] = None

# 检查输入是否完整
inputs_complete = (
    st.session_state["erpsku"] and
    st.session_state["country"] and
    st.session_state["zip_code"]
)

# 如果是加拿大，还需要省份信息
if st.session_state["country"] == "加拿大":
    inputs_complete = inputs_complete and st.session_state["province"]

if inputs_complete:
    if st.session_state["erpsku"] and st.session_state["country"] and st.session_state["zip_code"]:
        # 将中文国家名转换为国家代码
        country_code = cn_to_country_code.get(st.session_state["country"])

        if country_code:
            with st.spinner('计算物流成本中...'):
                # 调用物流成本计算函数
                # 注意：这里需要替换为实际的物流计算函数
                if country_code == "CA":
                    zj = lc.estimate_logistics_cost(
                        erp_sku=st.session_state["erpsku"],
                        country=country_code,
                        zip_code=st.session_state["zip_code"],
                        state=st.session_state["province"]
                    )
                else:

                    zj = lc.estimate_logistics_cost(
                        erp_sku=st.session_state["erpsku"],
                        country=country_code,
                        zip_code=st.session_state["zip_code"]
                    )

                # 模拟数据 - 实际使用时请替换为真实函数调用
                # zj = [
                #     {
                #         "supplier": "供应商A",
                #         "express": "快递方式1",
                #         "warehouse": "仓库A",
                #         "cost": 15.99
                #     },
                #     {
                #         "supplier": "供应商B",
                #         "express": "快递方式2",
                #         "warehouse": "仓库B",
                #         "cost": 12.50
                #     },
                #     {
                #         "supplier": "供应商C",
                #         "express": "快递方式3",
                #         "warehouse": "仓库C",
                #         "cost": 18.75
                #     }
                # ]

            if zj:
                # 创建数据表格
                st.subheader("物流成本计算结果")

                # 准备表格数据
                table_data = []
                for item in zj:
                    table_data.append({
                        "总费用": f"{item.get('cost', 0):.2f}",
                        "供应商": item.get('supplier', ''),
                        "快递方式": item.get('express', ''),
                        "仓库": item.get('warehouse', ''),
                        "住宅费": f"{item.get('house_cost', 0):.2f}",
                        "清关费": f"{item.get('clearance_fee', 0):.2f}",
                        "货型附加费": f"{item.get('goods_type_surcharge', 0):.2f}",
                        "其它附加费": f"{item.get('other_cost', 0):.2f}",
                        "特殊邮编附加费": f"{item.get('special_surcharge', 0):.2f}",
                        "能源附加费": f"{item.get('energy_surcharge', 0):.2f}",
                        "快递费": f"{item.get('delivery_cost', 0):.2f}",
                        "燃油附加费": f"{item.get('bunker_surcharge', 0):.2f}",
                        "旺季附加费": f"{item.get('peak_season_surcharge', 0):.2f}",
                        "出库费": f"{item.get('out_bound_cost', 0):.2f}"
                    })

                # 转换为DataFrame并显示
                df = pd.DataFrame(table_data)
                st.dataframe(df, use_container_width=True)

                # 添加下载按钮
                csv = df.to_csv(index=False).encode('utf-8')
                st.download_button(
                    label="下载结果CSV",
                    data=csv,
                    file_name='logistics_costs.csv',
                    mime='text/csv'
                )
            else:
                st.warning("未找到物流方案")
        else:
            st.error("无效的国家选择，请重新选择")
    else:
        st.info("请输入ERP SKU、选择国家并填写邮编以计算物流成本")
else:
    # 显示不同的提示信息
    if st.session_state["country"] == "加拿大" and not st.session_state["province"]:
        st.error("请输入ERP SKU、邮编和省份（加拿大必填）")
    else:
        st.info("请输入ERP SKU、选择国家并填写邮编以计算物流成本")